package com.wdl.modules.myhouse.security.handler;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.wdl.modules.myhouse.entity.UserEntity;
import com.wdl.modules.myhouse.security.common.SecurityConstant;
import com.wdl.modules.myhouse.security.entity.UserInfo;
import com.wdl.modules.myhouse.service.UserService;
import com.wdl.modules.myhouse.common.Result;
import com.wdl.modules.myhouse.utils.util.DateUtil;
import com.wdl.modules.myhouse.utils.util.JsonUtil;
import com.wdl.modules.myhouse.utils.util.RedisUtil;
import com.wdl.modules.myhouse.vo.UserVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @author 昏昏的君
 */
@Component
public class SuccessHandler implements AuthenticationSuccessHandler {


    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private UserService userService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {


        UserInfo user = (UserInfo) authentication.getPrincipal();
        //返回token
        Result<UserVo> res = new Result<UserVo>().ok();
        //jwt中存入uid
        String token = JWT.create()
                .withClaim(SecurityConstant.TOKEN_FIELD, user.getId())
                .withExpiresAt(DateUtil.datePushBackByDays(new Date(), SecurityConstant.JWT_TIME_OUT))
                .sign(Algorithm.HMAC256(SecurityConstant.TOKEN_SIGN));
        //持久化，redis存入全量用户信息
        user.setToken(token);
        redisUtil.setValue(user.getId().toString(), JsonUtil.obj2String(user), RedisUtil.getTimeOut(1, 3), TimeUnit.HOURS);

        //封装用户vo
        UserVo userVo = new UserVo();
        UserEntity userDesc = userService.getUserByUserId(user.getId());
        BeanUtils.copyProperties(userDesc, userVo);
        userVo.setToken(token);
        userVo.setUserName(user.getUsername());
        userVo.setId(user.getId());

        res.setData(userVo);
        res.setMsg("登录成功");
        response.getWriter().println(JsonUtil.obj2String(res));


    }
}